package com.quest.lock;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

public class LockTest {
    private static CustomExclusiveLock lock = new CustomExclusiveLock();
    private static Condition con1 = lock.newCondition();
    private static Condition con2 = lock.newCondition();
    private static volatile boolean flag = false;
    private static CountDownLatch latch = new CountDownLatch(1);
    private static ReentrantLock reentrantLock = new ReentrantLock();
    private static ReentrantReadWriteLock reentrantReadWriteLock = new ReentrantReadWriteLock();

    public static void aProcesser() throws InterruptedException {
        lock.lock();
        try {
            while (flag) {
                con1.await();
            }
            flag = true;
            System.out.println("★★★★★");
            con2.signal();
        }finally {
            lock.unlock();
        }
    }
    public static void bProcesser() throws InterruptedException {
        lock.lock();
        try {
            while (!flag) {
                con2.await();
            }
            flag = false;
            System.out.println("☆☆☆☆☆");
            con1.signal();
        }finally {
            lock.unlock();
        }
    }

    public static class PThread implements Runnable{

        @Override
        public void run() {
            try {
                latch.await();
                aProcesser();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
    public static class CThread implements Runnable{

        @Override
        public void run() {
            try {
                latch.await();
                bProcesser();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
    public static void main(String[] args) {
        int threadLength = 10;
        for (int i = 0; i < threadLength; i++) {
            Thread t1 = new Thread(new PThread());
            t1.start();
        }
        for (int i = 0; i < threadLength; i++) {
            Thread t2 = new Thread(new CThread());
            t2.start();
        }
        latch.countDown();
    }
}
